package com.zhanglijie.improve.atomic.one;

import com.zhanglijie.improve.unsafe.MyUnsafe;

import sun.misc.Unsafe;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/30 0030 23:16
 *
 * 本质 c++; lock+cmpxchgl
 */
public class CasDemo {
      volatile    int a;
    public static void main(String[] args) throws Exception {
        final CasDemo casDemo = new CasDemo();
        casDemo.casOperateOne(MyUnsafe.getUnsafe());
    }

    private void casOperateOne(Unsafe unsafe) throws NoSuchFieldException {

        new Thread(()->{
            for (int i = 1; i < 10; i++) {
                try {
                    incre(i,unsafe);
                    System.out.println( a);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(()->{
            for (int i =10; i <20; i++) {
                try {
                    incre(i,unsafe);
                    System.out.println(a);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void incre(int i, Unsafe unsafe) throws NoSuchFieldException {
          long offset ;
        do{
          offset  = unsafe.objectFieldOffset(CasDemo.class.getDeclaredField("a"));
        }while (!unsafe.compareAndSwapInt(this,offset,i-1,i));
    }
}
